<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/login.css">
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <title>登录页面</title>
</head>
<body>
    <!-- 导航栏 -->
    <div class="nav">
        网页聊天
    </div>

    <!-- 主窗口区 -->
    <div class="login-container">
        <div class="login-dialog">
            <h3>登录</h3>
            <div class="row">
                <span>用户名</span>
                <input type="text" id="username">
            </div>
            <div class="row">
                <span>密码</span>
                <input type="password" id="password">
            </div>
            <div class="row">
                <button id="submit">登录</button>
            </div>
            <!-- 添加注册按钮 -->
            <div class="row">
                <button id="register">注册</button>
            </div>
        </div>
    </div>
</body>

<script>
    let submit = document.getElementById('submit');
    submit.onclick = function() {
        let username = document.getElementById('username').value;
        let password = document.getElementById('password').value;
        $.ajax({
            type: 'POST',
            url: '/user/login',
            data: {
                username: username,
                password: password
            },
            success: function(res) {
                if (res.code === 200) {
                    // 把token保存到localStorage中
                    localStorage.setItem("user_token_header", res.data);
                    alert('登录成功');
                    window.location.href = '/client.html';
                }else{
                    alert('登录失败');
                }
            }
        })
    }
    
    // 添加注册按钮点击事件
    let register = document.getElementById('register');
    register.onclick = function() {
        let username = document.getElementById('username').value;
        let password = document.getElementById('password').value;
        $.ajax({
            type:'post',
            url:'/user/register',
            data:{
                username:username,
                password:password
            },
            success:function(res){
                if(res.code === 200){
                    // 把token保存到localStorage中
                    localStorage.setItem("user_token_header", res.data);
                    alert('注册成功');
                    window.location.href = '/client.html';
                }else{
                    alert(res.errmsg);
                }
            }
        });
    }
</script>
</html>